package edu.hebtu.controller;

import edu.hebtu.mapper.impl.*;
import edu.hebtu.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
public class TrainerController {

    private final DistributionMapper distributionMapper;
    private final AppointmentMapper appointmentMapper;
    private final TimeSlotMapper timeSlotMapper;
    private final SubjectMapper subjectMapper;
    private final RepairMapper repairMapper;
    private final UserMapper userMapper;
    private final CarMapper carMapper;

    @Autowired
    public TrainerController(DistributionMapper distributionMapper,
                             AppointmentMapper appointmentMapper,
                             TimeSlotMapper timeSlotMapper,
                             SubjectMapper subjectMapper,
                             RepairMapper repairMapper,
                             UserMapper userMapper,
                             CarMapper carMapper) {
        this.distributionMapper = distributionMapper;
        this.appointmentMapper = appointmentMapper;
        this.timeSlotMapper = timeSlotMapper;
        this.subjectMapper = subjectMapper;
        this.repairMapper = repairMapper;
        this.userMapper = userMapper;
        this.carMapper = carMapper;
    }

    @RequestMapping("/Trainer_userInfo")
    public String Trainer_userInfo(Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Distribution> distributions = distributionMapper.findById(null);
        distributions.removeIf(aValue -> !user.getUserId().equals(aValue.getCoachId()));
        List<User> users = userMapper.findById(null);
        boolean flag;
        for (Iterator<User> userIterator = users.iterator(); userIterator.hasNext(); ) {
            User user1 = userIterator.next();
            flag = false;
            for (Distribution distribution : distributions) {
                if (user1.getUserId().equals(distribution.getUserId())) {
                    flag = true;
                    break;
                }
            }
            if (user1.getState().trim().equals("appear")) user1.setState("正常");
            if (!flag) userIterator.remove();
        }
        model.addAttribute("users", users);
        return "tables/table-trainer-userInfo";
    }

    @RequestMapping("/Trainer_carInfo")
    public String Trainer_carInfo(Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Car> cars = carMapper.findById(null);
        cars.removeIf(aValue -> !user.getUserId().equals(aValue.getCustodian()));
        for (Car car : cars) {
            if (car.getState().trim().equals("appear")) car.setState("正常");
            if (car.getState().trim().equals("repair")) car.setState("修理中");
        }
        model.addAttribute("cars", cars);
        return "tables/table-trainer-carInfo";
    }

    @RequestMapping("/Trainer_editCar/{carId}")
    public String Trainer_editCar(@PathVariable("carId") String carId, Model model) {
        Car car = carMapper.findById(carId).get(0);
        model.addAttribute("car", car);
        if (car.getState().trim().equals("repair")) model.addAttribute("msg", "修理中");
        return "edit/edit-trainer-car";
    }

    @RequestMapping("/editTrainerCar")
    public String editTrainerCar(Car car, Model model) {
        if (carMapper.update(car) == 1) {
            return "redirect:/Trainer_carInfo";
        } else {
            model.addAttribute("msg", "修改失败！！！");
            return "edit/edit-trainer-car";
        }
    }

    @RequestMapping("/Trainer_editCarRepair/{carId}")
    public String Trainer_editCarRepair(@PathVariable("carId") String carId, Model model) {
        Car car = carMapper.findById(carId).get(0);
        model.addAttribute("car", car);
        if (car.getState().trim().equals("repair")) model.addAttribute("msg", "修理中");
        return "edit/edit-trainer-car-repair";
    }

    @RequestMapping("/editTrainerCarRepair")
    public String editTrainerCarRepair(Car car, Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        Repair repair = new Repair();
        repair.setCarId(car.getCarId());
        repair.setRepairTime(new Date());
        repair.setUserId(user.getUserId());
        if (carMapper.update(car) == 1 && repairMapper.add(repair) == 1) {
            return "redirect:/Trainer_carInfo";
        } else {
            model.addAttribute("msg", "修改失败！！！");
            return "edit/edit-trainer-car-repair";
        }
    }

    @RequestMapping("/trainer_appointmentInfo")
    public String trainer_appointmentInfo(Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Car> cars = carMapper.findById(null);
        cars.removeIf(aValue -> !user.getUserId().equals(aValue.getCustodian()));
        List<Appointment> appointments = appointmentMapper.findById(null);
        for (Iterator<Appointment> appointmentIterator = appointments.iterator(); appointmentIterator.hasNext(); ) {
            Appointment appointment = appointmentIterator.next();
            boolean flag = false;
            for (Car car : cars) {
                if (car.getCarId().equals(appointment.getCarId())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {            //去掉非该教练车辆的预约信息
                appointmentIterator.remove();
                continue;
            }
            TimeSlot timeSlot = timeSlotMapper.findById(appointment.getTimeSlotId()).get(0);
            Calendar now = Calendar.getInstance();      //当前的时间
            now.set(Calendar.SECOND, 0);                //秒和毫秒清零
            now.set(Calendar.MILLISECOND, 0);
            Calendar time = Calendar.getInstance();
            Calendar startTime = Calendar.getInstance();
            startTime.setTime(timeSlot.getStartTime());             //时间段的开始时间（时和分）
            time.setTime(appointment.getAppointmentDate());                     //预约的日期，不包括时间
            time.set(Calendar.SECOND, 0);               //秒和毫秒清零
            time.set(Calendar.MILLISECOND, 0);
            time.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段开始的时和分
            time.set(Calendar.MINUTE, startTime.get(Calendar.MINUTE));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");   //格式化日期时间
            String timeStr = simpleDateFormat.format(time.getTime()) + " - ";
            if (time.compareTo(now) < 0) {      //去掉预约的日期在当前时间之前的信息
                appointmentMapper.delete(appointment);
                appointmentIterator.remove();
            } else {
                Calendar endTime = Calendar.getInstance();
                endTime.setTime(timeSlot.getEndTime());             //时间段的结束
                time.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段结束的时和分
                time.set(Calendar.MINUTE, endTime.get(Calendar.MINUTE));
                timeStr += simpleDateFormat.format(time.getTime());
                appointment.setTimeSlotId(timeStr);                 //获取预约的时间段（年月日时分）
                appointment.setUserId(userMapper.findById(appointment.getUserId()).get(0).getName() + "(" + appointment.getUserId() + ")"); //获取学员名
                appointment.setCarId(carMapper.findById(appointment.getCarId()).get(0).getId() + "号车(" + carMapper.findById(appointment.getCarId()).get(0).getLicense() +  ")"); //获取车牌号
                appointment.setSubjectId(subjectMapper.findById(appointment.getSubjectId()).get(0).getSubjectName());   //获取科目名称
            }
        }

        model.addAttribute("appointments", appointments);
        return "tables/table-trainer-appointment";
    }

    @RequestMapping("/trainer_deleteAppointment/{appointmentId}")
    public String trainer_deleteAppointment(@PathVariable("appointmentId") String appointmentId, Model model) {
        Appointment appointment = appointmentMapper.findById(appointmentId).get(0);

        appointment.setUserId(userMapper.findById(appointment.getUserId()).get(0).getName() + "(" + appointment.getUserId() + ")"); //获取学员名

        appointment.setCarId(carMapper.findById(appointment.getCarId()).get(0).getId() + "号车(" + carMapper.findById(appointment.getCarId()).get(0).getLicense() +  ")"); //获取车牌号

        appointment.setSubjectId(subjectMapper.findById(appointment.getSubjectId()).get(0).getSubjectName());                       //获取科目名称

        TimeSlot timeSlot = timeSlotMapper.findById(appointment.getTimeSlotId()).get(0);
        Calendar time = Calendar.getInstance();
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(timeSlot.getStartTime());             //时间段的开始时间（时和分）
        time.setTime(appointment.getAppointmentDate());                     //预约的日期，不包括时间
        time.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段开始的时和分
        time.set(Calendar.MINUTE, startTime.get(Calendar.MINUTE));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");   //格式化日期时间
        String timeStr = simpleDateFormat.format(time.getTime()) + " - ";
        Calendar endTime = Calendar.getInstance();
        endTime.setTime(timeSlot.getEndTime());             //时间段的结束
        time.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段结束的时和分
        time.set(Calendar.MINUTE, endTime.get(Calendar.MINUTE));
        timeStr += simpleDateFormat.format(time.getTime());
        appointment.setTimeSlotId(timeStr);                                                                                         //获取预约的时间段（年月日时分）

        model.addAttribute("appointment", appointment);
        return "delete/delete-trainer-appointment";
    }

    @RequestMapping("/deleteAppointment")
    public String deleteAppointment(Appointment appointment) {
        appointmentMapper.delete(appointment);
        return "redirect:/trainer_appointmentInfo";
    }

}
